package com.example.quizamination.ui.main

import android.icu.text.DateFormat.getDateInstance
import android.icu.util.Calendar
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.activity.OnBackPressedCallback
import androidx.navigation.fragment.findNavController
import com.example.quizamination.R
import com.example.quizamination.databinding.FragmentWelcomeBinding
import com.google.android.material.datepicker.CalendarConstraints
import com.google.android.material.datepicker.MaterialDatePicker
import com.google.android.material.snackbar.Snackbar
import java.text.SimpleDateFormat

class WelcomeFragment : Fragment() {
    private var _binding: FragmentWelcomeBinding? = null
    private val binding: FragmentWelcomeBinding
        get() = _binding!!
    private var birthDate: String = ""

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val onBackPressedCallback = object : OnBackPressedCallback(true) {
            override fun handleOnBackPressed() {
                requireActivity().finish()
            }
        }
        requireActivity().onBackPressedDispatcher.addCallback(this, onBackPressedCallback)
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
    ): View? {
        _binding = FragmentWelcomeBinding.inflate(inflater, container, false)
        binding.nextButton.setOnClickListener {
            findNavController().navigate(R.id.action_welcomeFragment_to_mainFragment)
        }
        setupBirthDatePicker()
        return binding.root
    }
    private fun setupBirthDatePicker()
    {
        val calendar: Calendar = Calendar.getInstance()
        val calendarConstraints: CalendarConstraints = CalendarConstraints.Builder()
            .setOpenAt(calendar.timeInMillis).build()
        val calendarFormater = getDateInstance()
        val birthDatePicker = MaterialDatePicker.Builder.datePicker()
            .setTitleText(getString(R.string.birth_date_picker_title))
            .setCalendarConstraints(calendarConstraints)
            .build()
        binding.birthDateButton.setOnClickListener {
            birthDatePicker.addOnPositiveButtonClickListener {
                calendar.timeInMillis = it
                birthDate = calendarFormater.format(calendar.time)
                Snackbar.make(
                    binding.birthDateButton,
                    birthDate,
                    Snackbar.LENGTH_LONG
                ).show()
            }
            birthDatePicker.show(childFragmentManager, "birthDatePicker")
        }
    }
}